<?php
use Wdl\helper\FrontHelper;
use Wdl\helper\webHelper;
/**
 * 这个是聊天的接口
 */
global $_GPC, $_W;
$uniacid =  webHelper::bindUniacid();
$openid = $_W['openid'];
$uid = $_W['member']['uid'];
if (empty($uid)) {
    $fans = mc_fansinfo($openid, 0, $this->_uniacid);
    $uid = $fans['uid'];
}
 
load()->func('tpl');
load()->func('logging');  
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

if($operation =='ajaxMsgList'){
    FrontHelper::check_login();
        $fromAccount = $_GPC['fromAccount'];
        $toAccount   = $_GPC['toAccount'];
        
        $fromAccountPic = $_GPC['fromAccountPic'];
        $toAccountPic   = $_GPC['toAccountPic'];
        

        $config = array(
            'fromAccount'=>$fromAccount,
            'fromAccountPic'=> $fromAccountPic,
            'toAccount'=> $toAccount,
            'toAccountPic'=> $toAccountPic,
        );    
        if(!$fromAccount || !$toAccount) {
           $this->result(1, "参数错误",[]);   
        }
        
        $pageNum = 10;
        $page = max(1, $_GPC['page']);
        $pagesize = 10;
        $startlimit = ($page-1)* $pagesize;
        
        $condition  = " ( From_Account='$fromAccount' AND To_Account='$toAccount' ) OR  ( From_Account='$toAccount' AND To_Account='$fromAccount' ) ";
        if(empty($_GPC['total'])){
            $count = pdo_fetchcolumn(" SELECT COUNT(*) FROM  ".tablename("kbwdl_im_msg")." where $condition ");
            $totalpage = ceil($count / $pagesize);
        }else{
            $totalpage = $_GPC['total'];
        }
       
        /**/
        $sql =  "SELECT *  FROM ".tablename("kbwdl_im_msg")." where $condition order by id desc limit $startlimit, $pagesize";

        $data  = pdo_fetchall( $sql ); 
        krsort( $data, SORT_NUMERIC);
        $temp_data = [];
        if(is_array($data))  {
            foreach ($data as $key => $item) {            
            
                $temp_data[] = webHelper:: format_message($config, $item);
             
            }
        }
    $ret = [
        'totalpage' => $totalpage,
        'msglist' => $temp_data
    ];
     $this->result(0, "消息列表", $ret);
}
/**
 * 获取当前最新一条信息
 * fromAccount = 聊天对方的
 * toAccount  = 当前聊天人的
 */
if($operation =='LastMsg'){
        $fromAccount = $_GPC['fromAccount'];
        $toAccount   = $_GPC['toAccount'];
        
        $fromAccountPic = $_GPC['fromAccountPic'];
        $toAccountPic   = $_GPC['toAccountPic'];
        
        $lastid = max(1,$_GPC['lastid']);

        $config = array(
            'fromAccount'=>$fromAccount,
            'fromAccountPic'=> $fromAccountPic,
            'toAccount'=> $toAccount,
            'toAccountPic'=> $toAccountPic,
        );    
        if(!$fromAccount || !$toAccount) {
           $this->result(1, "参数错误",[]);   
        }
        $condition  = "   From_Account='$toAccount' AND To_Account='$fromAccount' and id > $lastid ";
       
        $sql =  "SELECT *  FROM ".tablename("kbwdl_im_msg")." where $condition order by id desc ";        
        $item = pdo_fetch($sql);
        $ret = [];
        if(!empty($item)){
            $ret =  webHelper:: format_message($config, $item);
        }
        /*设置已读*/
        pdo_update("kbwdl_im_recent", ['unread'=>0,'uniacid'=> $uniacid], ['acount'=> $fromAccount,'from_acount'=> $toAccount]);
     
        if($fromAccount && $toAccount) {         
            $where  = " isread=0 AND ( From_Account='$toAccount' AND To_Account='$fromAccount' ) ";            
            $data['isread'] = 1;
            pdo_query("update ".tablename("kbwdl_im_msg")." set isread=1 WHERE $where");
            
        }   
        $this->result(0, "最新消息", $ret);
}

/**
     * 最近7天的联系人
     */
 if($operation =='recent'){  
        
        $username = $_GPC['username'];     
        $fk =  $_GPC['fk']; //非客服
        $sqladd = " (  NOW() < DATE_ADD(addtime,INTERVAL 7 day) )  and ( acount='$username')";
      
        $sql = "select * from ". tablename("kbwdl_im_recent") ." where $sqladd order by addtime desc ";
        $data = pdo_fetchall($sql);
        $temp_data = [];
        $recent_acount = [];
       
        if (is_array($data)) {
            foreach ($data as $key => $item) {
                //文本消息 
                if ($item['msgtype'] == 'TIMTextElem') {
                    $temp = json_decode($item['lastmsg']);
                    $content = $temp->Text;
                } else if ($item['msgtype'] == 'TIMImageElem') {
                    //自定义消息  /
                    $temp = json_decode($item['lastmsg']);
                    
                    $content = htmlspecialchars_decode('图片消息');
                    
                } else {
                    $temp = json_decode($item['lastmsg']);
                    $content = htmlspecialchars_decode($temp->Text);
                }
                $account = json_decode($item['from_acount_info'], true);
                $recent_acount[] = $item['acount'];
                $temp_data[] = array(
                    'username' => empty($account['username'])? '访客': $account['username'],
                    'thumb' => empty($account['thumb'])? toimage('../addons/kbwdl_shequzufang/style/images/get_avatar.png'):toimage($account['thumb']), 
                    'MsgTimeStamp' => date('m月d日',strtotime($item['addtime'])),
                    'MsgShow' => $content,
                    'unread' => $item['unread'],
                    'To_Account'=> $item['from_acount'],                   
                );
            }
        }
        /*获取我主动发过的*/
        $sqladd = " uniacid='$uniacid' and (  NOW() < DATE_ADD(addtime,INTERVAL 7 day) )  and (  from_acount='$username')"; 
        $sql = "select * from ". tablename("kbwdl_im_recent") ." where $sqladd order by addtime desc ";
        $data = pdo_fetchall($sql);
       
        if (is_array($data)) {
            foreach ($data as $key => $item) {
                if(in_array($item['from_acount'], $recent_acount)){
                    continue;
                }
                //文本消息 
                if ($item['msgtype'] == 'TIMTextElem') {
                    $temp = json_decode($item['lastmsg']);
                    $content = $temp->Text;
                } else if ($item['msgtype'] == 'TIMImageElem') {
                    //自定义消息  /
                    $temp = json_decode($item['lastmsg']);
                    
                    $content = htmlspecialchars_decode('图片消息');
                    
                } else {
                    $temp = json_decode($item['lastmsg']);
                    $content = htmlspecialchars_decode($temp->Text);
                }
                $account = json_decode($item['from_acount_info'], true);
                $temp_data[] = array(
                    'username' => empty($account['username'])? '访客': $account['username'],
                    'thumb' => empty($account['thumb'])? toimage('../addons/kbwdl_shequzufang/style/images/get_avatar.png'):toimage($account['thumb']), 
                    'MsgTimeStamp' => date('m月d日',strtotime($item['addtime'])),
                    'MsgShow' => $content,
                    'unread' => $item['unread'],
                    'To_Account'=> $item['acount'],
                );
            }
        }
        
         echo json_encode(['errno'=>0,'data'=>$temp_data]);
         exit;
     
    }

/*保存聊天数据*/
if($operation == 'saveMsg'){
    $msginfo = $_GPC ;
    $savedata = array(
        'From_Account' => $msginfo['froomAccount'],
        'To_Account' => $msginfo['sendto'],
        'msgType' => $msginfo['msgType'],
        'msgContent'=> '',
        'addTime'=> date('Y-m-d H:i:s',$msginfo['time']),/*date('Y-m-d H:i:s', TIMESTAMP),*/
        'ip'=> $msginfo['time'],
        'isread'=>0,
        'uniacid'=>$uniacid,
    );
    if($msginfo['msgType'] =='TIMTextElem'){
         $stext= array('Text'=> $msginfo['msgcontent']);
        
    }
    if($msginfo['msgType'] =='TIMCustomElem'){
         $stext= array('Text'=>$msginfo['msgcontent'], 'Data'=> $msginfo['data'],'Ext'=> $msginfo['url']);
        
    }
    /*图片消息*/
    if($msginfo['msgType'] == 'TIMImageElem'){
        $pp1 = str_replace("&#039;", '&#034;', $msginfo['msgcontent']  );
        
        $stext= array('Text'=>'图片消息', 'Data'=>$pp1,'Ext'=> $msginfo['url']);
    }
    /*上一次的聊天记录*/
    $sqladd = " uniacid='$uniacid' and From_Account='".$msginfo['froomAccount']."' and  To_Account='".$msginfo['sendto']."'";
    $sql = "select * from".tablename("kbwdl_im_msg"). " where $sqladd  order by id desc ";
    $lastmsg = pdo_fetch($sql);  

    /*插入新记录*/
    $savedata['msgContent'] = json_encode($stext);
        pdo_insert("kbwdl_im_msg", $savedata);
        $savedata['id'] = pdo_insertid();
        $returnData['errno'] = 0;  
        $returnData['errno'] = 0;       
        $returnData['data'] =  webHelper:: format_message(['fromAccount'=> $savedata['From_Account']], $savedata);
        $returnData['des'] = '保存数据成功';
       /*保存聊天对象到最近7天联系人表*/
         $sql = "select * from " . tablename("kbwdl_im_recent") . " where  acount='".$msginfo['sendto']."' and from_acount='".$msginfo['froomAccount']."' ".
                 " and  uniacid='$uniacid' and  (  NOW() < DATE_ADD(addtime,INTERVAL 7 day) )";
         $recent =  pdo_fetch($sql);
         if(empty($recent)){
             //$account =  $_GPC['account'];
             $account = pdo_fetch("select * from ".tablename("kbwdl_broker")." where openid='".$msginfo['froomAccount']."' and uniacid='$uniacid' order by id desc ");
             
             //聊天对象信息            
              pdo_insert("kbwdl_im_recent", array(
                  'uniacid'=> $uniacid,
                  'acount'=>$msginfo['sendto'], 
                  'from_acount'=>$msginfo['froomAccount'],
                  'lastmsg' => $savedata['msgContent'],
                  'msgtype'=> $savedata['msgType'],                 
                  'from_acount_info' => json_encode(['thumb'=>$account['avatar'],'username'=> !empty($account['truename'])?$account['truename']: $account['nickname'] ]),
                  'addtime'=>date('Y-m-d H:i:s', $msginfo['time']),
                   'unread'=>1
                  ));
         }else{
            $account = pdo_fetch("select * from ".tablename("kbwdl_broker")." where openid='".$msginfo['froomAccount']."' and uniacid='$uniacid' order by id desc ");
             
             pdo_update("kbwdl_im_recent", 
                     array('addtime'=>date('Y-m-d H:i:s', $msginfo['time']),
                     'lastmsg' => $savedata['msgContent'],
                     'msgtype'=> $savedata['msgType'], 
                     'from_acount_info' => json_encode(['thumb'=>$account['avatar'],'username'=>!empty($account['truename'])?$account['truename']: $account['nickname'] ]),    
                     'unread'=> $recent['unread']+1,
                    ), ['id'=>$recent['id']]  );
         }
        /**/ 
 
        /*发送微信通知检测5分钟不回复就发送 OPENTM202119578 用户咨询提醒 */  
      
        //$detailurl = $_W['siteroot'].$this->createMobileUrl("im").'#recentlist';
        $siteurl =  $_W['siteroot']. "app/";  
        $detailurl = $siteurl. $this->createMobileUrl("im").'#recentlist';
        //
        $ret = pdo_fetch("select count(*) as num from ".tablename("kbwdl_im_msg"). " where $sqladd ");
       /* $toinfo= pdo_fetch("select openid,iskefu from ".tablename("kbwdl_im_usersign")." where signsrc='".$msginfo['sendto']."'");
        $fromAccountName = pdo_fetchcolumn("select username from ".tablename("kbwdl_im_usersign")." where signsrc='".$msginfo['froomAccount']."'");*/
        /*$msginfo['froomAccount']*/
      
        if($ret['num']==1){
            $openid = $toinfo['openid'];
            /*第一次会话发通知*/            
           $returnData['notice'] =  wdl_im_notice($msginfo , $this);
             $returnData['jscallback'] = 'SendWellcomeMsg';
            /*发送 客服默认回复消息
            $iskefu = pdo_fetch("select * from ".tablename("kbwdl_im_usersign")." where  uniacid='$uniacid' and signsrc='".$msginfo['sendto']."' and iskefu=1");
           
            if(!empty($iskefu['desc'])){
                $returnData['jscallback'] = 'SendWellcomeMsg';
                $returnData['defmsg'] = $iskefu['desc'];
            } */
        }else{            
          
            $limittime = $msginfo['time'] - 100; /*两分钟提醒一次*/
           /* logging_run($limittime.' >'. $ret['ip'] );  */    
            if(!empty($lastmsg)){  
                /*客服和客户有过聊天记录*/ 
                if($lastmsg['isread']==1){
                   if( $limittime > $lastmsg['ip']){
                        $openid = $toinfo['openid'];
                       
                       $returnData['notice'] =  wdl_im_notice( $msginfo, $this); 
                        /*发送 客服默认回复消息
                        $iskefu = pdo_fetch("select * from ".tablename("kbwdl_im_usersign")." where  uniacid='$uniacid' and  signsrc='".$msginfo['sendto']."' and iskefu=1");
                     
                        if(!empty($iskefu['desc'])){
                            $returnData['jscallback'] = 'SendWellcomeMsg';
                            $returnData['defmsg'] = $iskefu['desc'];
                        }*/
                    } 
                }
                if($lastmsg['isread']==0){ /*未读消息一直发*/
                    $openid = $toinfo['openid'];
                    /*查询上一条记录的情况*/
                    $lastfirst = pdo_fetchcolumn("select count(*) as num from ".tablename("kbwdl_im_msg")." where $sqladd  and isread=0  ");
                    if($lastfirst==1){
                       $returnData['notice'] = wdl_im_notice( $msginfo, $this); 
                    }else{
                        $last = pdo_fetch("select * from ".tablename("kbwdl_im_msg")." where $sqladd and id < '".$lastmsg['id']."' and isread=0 order by id desc ");
                        if($limittime+50 > $last['ip']){                            
                          
                          $returnData['notice'] =  wdl_im_notice( $msginfo, $this); 
                        }
                    }
                }

                
            }
        }
        echo json_encode($returnData);
        exit;
    
}


 
     /*发送模板消息到下单人的微信 */
    function wdl_im_notice($msginfo , $pobject)
    {  
        global $_GPC, $_W;
        $uniacid = $pobject->_uniacid;
        /*模板顺序*/        
        $fromacount = $msginfo['froomAccount'];
        $sendto = $msginfo['sendto'];
        
        $from = pdo_fetch("select * from ".tablename("kbwdl_broker") ." where openid='$fromacount' and uniacid='$uniacid'");
        $touser = pdo_fetch("select * from ".tablename("kbwdl_broker") ." where openid='$sendto' and uniacid='$uniacid'");
        /*获取公众号access_token*/
        return $pobject-> _send_notice_account( 'feed_notice',
                 '小程序微聊消息', 
                 '发送人：'. $from['nickname'] ,
                 '内容：' .$msginfo['msgcontent'],
                 '备注: 请及时打开小程序处理。', $touser['gzhopenid']);              
        
        
    }
 
?>
